package com.express.service.impl;

import com.express.entity.Parameter;
import com.express.entity.Token;
import com.express.service.TokenService;
import com.express.sys.mapper.TokenMapper;
import com.express.util.RequestResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author lingzhouf
 */
@Service
public class TokenServiceImpl implements TokenService {

  @Autowired
  TokenMapper tokenMapper;

  @Override
  public void add(Token token) {
    this.tokenMapper.add(token);
  }
  @Override
  public Token get(Token token) {
    return this.tokenMapper.get(token);
  }
  @Override
  public void update(Token token) {
    this.tokenMapper.update(token);
  }
  @Override
  public boolean verify(String tokenStr) {
    Token t = new Token();
    t.setToken(tokenStr);
    Token token = this.tokenMapper.get(t);
    if ((token != null) && (token.getToken() != null)) {
      Date now = new Date();
      Long s = Long.valueOf(now.getTime() - token.getExpireTime().getTime());
      if (s.longValue() < 0L) {
        token.setUpdateTime(now);
        token.setExpireTime(new Date(now.getTime() + 7200000L));
        this.tokenMapper.update(token);
        return true;
      }
      this.tokenMapper.remove(token.getToken());
    }
    return false;
  }
  @Override
  public void remove(String token) {
    this.tokenMapper.remove(token);
  }

  @Override
  public Token getToken() {
    Token token = new Token();
    HttpServletRequest request = RequestResponseUtil.getRequest();
    token.setToken(request.getHeader("token"));
    return this.tokenMapper.get(token);
  }
  @Override
  public void updateOtherInfo(Token token) {
    this.tokenMapper.updateOtherInfo(token);
  }
  @Override
  public void clearExpireToken() {
    this.tokenMapper.clearExpireToken();
  }

  @Override
  public List<Parameter> query() {
    return this.tokenMapper.queryParamer();

  }

  @Override
  public Token getToken(String token) {
    return this.tokenMapper.get(token);
  }
}
